/**  
* @Title: TaobaoController.java 
* @Description:
* @Copyright: Copyright (c) 2018
* @Company:http://www.sinocon.cn
* @author: Su.Yuanlin  
* @date 2019年4月11日  
* @QQ 314078331  
* @Like 流水落花春去也，天上人间
*/
package com.mtons.mblog.web.controller.admin;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.mtons.mblog.base.lang.Consts;
import com.mtons.mblog.base.lang.Result;
import com.mtons.mblog.base.utils.FileKit;
import com.mtons.mblog.modules.data.AnalysisVO;
import com.mtons.mblog.modules.data.SalesVo;
import com.mtons.mblog.modules.data.TableDataInfo;
import com.mtons.mblog.modules.entity.Product;
import com.mtons.mblog.modules.entity.Sales;
import com.mtons.mblog.modules.service.TaobaoService;
import com.mtons.mblog.web.controller.BaseController;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

/**
 * @Title: TaobaoController
 * @Description:
 * @author:Su.Yuanlin
 * @date 2019年4月11日
 */
@Controller("taobaoController")
@RequestMapping("/admin/taobao")
public class TaobaoController extends BaseController {
	@Autowired
	private TaobaoService taobaoService;

	@RequestMapping("/sales/list")
	public String list(ModelMap model, HttpServletRequest request) {
		List<Product> productAll = this.taobaoService.getProductAll();
		model.put("productList", productAll);

		model.put("begin", ServletRequestUtils.getStringParameter(request, "begin", ""));
		model.put("end", ServletRequestUtils.getStringParameter(request, "end", ""));
		model.put("productId", ServletRequestUtils.getStringParameter(request, "productId", ""));
		model.put("kw", ServletRequestUtils.getStringParameter(request, "kw", ""));

		return "/admin/taobao/sales-list";
	}

	@RequestMapping("/sales/add")
	public String addSales(ModelMap model) {
		List<Product> productAll = this.taobaoService.getProductAll();
		model.put("productList", productAll);

		return "/admin/taobao/sales-add";
	}

	@RequestMapping("/sales/update")
	public String salesUpdate(Sales view) {
		if (view != null) {
			this.taobaoService.saveOrUpdateSales(view);
		}
		return "redirect:/admin/taobao/sales/list";
	}

	@RequestMapping("/sales/update/{id}")
	public String salesEdit(ModelMap model, @PathVariable String id) {
		Sales sales = this.taobaoService.getSalesById(id);
		List<Product> productAll = this.taobaoService.getProductAll();

		model.put("productList", productAll);
		model.put("view", sales);

		return "/admin/taobao/sales-add";
	}

	@RequestMapping("/saleslist")
	public @ResponseBody TableDataInfo salesList(HttpServletRequest request) {
		String m = DateUtil.thisMonth() + 1 < 10 ? "0" + (DateUtil.thisMonth() + 1) : (DateUtil.thisMonth() + 1) + "";
		String monthOfFirstDay = DateUtil.thisYear() + "-" + m + "-01";

		String begin = ServletRequestUtils.getStringParameter(request, "begin", monthOfFirstDay);
		String end = ServletRequestUtils.getStringParameter(request, "end", DateUtil.today());
		begin = StrUtil.isBlank(begin) ? monthOfFirstDay : begin;
		end = StrUtil.isBlank(end) ? DateUtil.today() : end;

		String productId = ServletRequestUtils.getStringParameter(request, "productId", "");
		String kw = ServletRequestUtils.getStringParameter(request, "kw", "");
		String isNatural = ServletRequestUtils.getStringParameter(request, "isNatural", "");

		Pageable pageable = wrapPageable();
		Page<SalesVo> page = this.taobaoService.getSalesByTime(pageable, begin, end, productId, kw, isNatural);

		return getDataTable(page);
	}

	@SuppressWarnings("rawtypes")
	@RequestMapping("/upload")
	public @ResponseBody Result importSales(@RequestParam("file") MultipartFile file) {
		if (null == file || file.isEmpty()) {
			return Result.failure("文件不能为空");
		} else {
			String suffix = FileKit.getSuffix(Objects.requireNonNull(file.getOriginalFilename()));
			if (!FileKit.checkExcelFileType(suffix)) {
				return Result.failure("请上传excel文件");
			}
			ImportParams params = new ImportParams();
			params.setTitleRows(0);
			params.setHeadRows(1);
			try {
				List<Sales> importExcel = ExcelImportUtil.importExcel(file.getInputStream(), Sales.class, params);
				this.taobaoService.addSales(buildSales(importExcel));
			} catch (Exception e) {
				e.printStackTrace();
				return Result.failure("读取excel文件错误");
			}
		}
		return Result.success();
	}

	@RequestMapping("/analysis")
	public @ResponseBody AnalysisVO getAnalysis(HttpServletRequest request){
		String m = DateUtil.thisMonth() + 1 < 10 ? "0" + (DateUtil.thisMonth() + 1) : (DateUtil.thisMonth() + 1) + "";
		String monthOfFirstDay = DateUtil.thisYear() + "-" + m + "-01";

		String begin = ServletRequestUtils.getStringParameter(request, "begin", monthOfFirstDay);
		String end = ServletRequestUtils.getStringParameter(request, "end", DateUtil.today());
		begin = StrUtil.isBlank(begin) ? monthOfFirstDay : begin;
		end = StrUtil.isBlank(end) ? DateUtil.today() : end;

		String productId = ServletRequestUtils.getStringParameter(request, "productId", "");
		String kw = ServletRequestUtils.getStringParameter(request, "kw", "");
		String isNatural = ServletRequestUtils.getStringParameter(request, "isNatural", "");
		String status = ServletRequestUtils.getStringParameter(request, "status", "");
		
		return this.taobaoService.getAnalysisData(productId, isNatural, begin, end, status, kw);
	}
	private List<Sales> buildSales(List<Sales> importList) {
		List<Sales> ret = new ArrayList<>();
		List<Product> productAll = this.taobaoService.getProductAll();
		// 存在合并单的情况，这里暂时不做处理
		importList.stream().filter(im -> ObjectUtil.isNotNull(im.getProductName()))
				.filter(im -> !Consts.order.CLOSE.equals(im.getStatus())).forEach(sl -> {
					Sales sales = this.taobaoService.getSalesByTaobaoOrder(sl.getTaobaoOrder());
					// ID设置
					if (ObjectUtil.isNotNull(sales)) {
						sl.setSalesId(sales.getSalesId());
					} else {
						sl.setSalesId(UUID.randomUUID().toString());
					}
					// 名称
					StringBuffer productNames = new StringBuffer();
					StringBuffer pns = new StringBuffer();
					StringBuffer productId = new StringBuffer();
					Arrays.asList(sl.getProductName().split(",")).stream().forEach(obj -> {
						productNames.append(getProductName(productAll, obj.toString(), pns, productId));
					});

					sl.setProductName(productNames.toString());
					sl.setProductId(productId.toString());
					sl.setBuyMark(pns.toString());
					ret.add(sl);
				});
		return ret;
	}

	private String getProductName(List<Product> p, String pname, StringBuffer remark, StringBuffer productId) {
		String productName = pname;
		String productNuber = "";
		for (Product product : p) {
			if (pname.indexOf(product.getProductName()) > -1) {
				productName = product.getProductName();
				remark.append(pname).append("-").append(product.getProductId()).append(",");
				productNuber = product.getProductId();
				break;
			}
		}
		productId.append(productNuber);
		return productName;
	}
}
